from llama_index.core.base.llms.types import ChatMessage

from app.llama_index.llms.openai import createOpenAI
from app.models import Message


def message_to_ChatMessage(messageDTO: Message):
    """数据库对象 转成 ChatMessage"""
    return ChatMessage(
        role=messageDTO.role,
        content=messageDTO.content,
        msg_id=messageDTO.id
    )

def chatMessage_to_message(chatMessage: ChatMessage,chat_id=None):
    """ChatMessage 转成数据库对象"""
    return Message(
        chat_id=chat_id,
        role=chatMessage.role,
        content=chatMessage.content,
    )



titleLlm=None
def generateChatTitle(user_msg:str):
    """生成聊天标题"""
    global titleLlm
    if not titleLlm:
        titleLlm=createOpenAI()
    messages = [
        ChatMessage(
            role="system", content="你是一个擅长根据用户发送的信息生成标题的助手,你只需要回复一个标题即可,字数限制为20个字",
        ),
        ChatMessage(role="user", content=user_msg),
    ]
    response=titleLlm.chat(messages)
    _message=response.message.content
    return f"{str(_message)}"